<template>
  <div class="w-full flex items-center">
    <el-date-picker
      v-model="beginTime"
      :type="dateType"
      :placeholder="props.placeholder"
      clearable
      class="mb-[0px]"
      v-if="dateType != 'date'"
      :value-format="valueFormat"
      :disabled-date="disabledStartDate"
    />
    <el-date-picker
      v-model="beginTime"
      type="date"
      :placeholder="props.placeholder"
      clearable
      :value-format="valueFormat"
      :disabled-date="disabledStartDate"
      class="mb-[0px]"
      v-else
    />
    <span style="width: 20px; text-align: center">至</span>
    <el-date-picker
      v-model="endTime"
      :type="dateType"
      :placeholder="props.placeholder"
      clearable
      :value-format="valueFormat"
      :disabled-date="disabledEndDate"
      class="mb-[0px]"
      v-if="dateType != 'date'"
      @change="(value) => changeMonth(value)"
    />
    <el-date-picker
      v-model="endTime"
      type="date"
      :placeholder="props.placeholder"
      clearable
      :value-format="valueFormat"
      :disabled-date="disabledEndDate"
      class="mb-[0px]"
      v-else
    />
    <el-select v-model="dateType" style="flex-basis: 145px; flex-shrink: 0" @change="typeChange">
      <el-option
        :label="item.label"
        :value="item.type"
        v-for="item in selectOptions"
        :key="item.type"
      />
    </el-select>
  </div>
</template>

<script setup>
import { formatDate } from '@/utils/formatTime';
const beginTime = defineModel("beginTime");
const endTime = defineModel("endTime");
const dateType = ref("date");
const valueFormat = ref("YYYY-MM-DD HH:mm:ss");
const props = defineProps({
  placeholder: {
    type: String,
    default: "",
  },
});
const selectOptions = [
  {
    label: "年月日",
    type: "date",
  },
  {
    label: "年月",
    type: "month",
  },
  {
    label: "年度",
    type: "year",
  },
];
//选择的时间类型改变
const typeChange = () => {
  beginTime.value = "";
  endTime.value = "";
};
//年月取月末，年取年末
const changeMonth= (value)=>{
  if (value != null) {
    let myDate = new Date(value);
    if (dateType.value == "month") {
      endTime.value = formatDate(new Date(myDate.getFullYear(), myDate.getMonth() + 1, 0)); // 获取本月最后一天
    } else {
      endTime.value = formatDate(new Date(myDate.getFullYear(), 11, 31)); // 月份是从0开始的，所以11代表12月，31是12月的最后一天
    }
  }
}
const disabledStartDate = (time) => {
  if (endTime.value == null) {
    return false; // 如果没有结束日期，则不禁用所有日期
  }
  return time.getTime() > new Date(endTime.value).getTime(); // 开始日期不能大于结束日期
}
const disabledEndDate = (time) => {
  if (beginTime.value == null) {
    return false; // 如果没有开始日期，则不禁用所有日期
  }
  return time.getTime() < new Date(beginTime.value).getTime(); // 开始日期不能大于结束日期
}
</script>

<style scoped lang="scss"></style>
